﻿using System;
using System.Drawing;
using System.IO;
using System.Windows.Media.Imaging;
using System.Drawing.Imaging;

namespace HomeService.Models
{
    public class ServiceRequestPhoto : ViewModelBase
    {
        private readonly byte[] _bytes;
        private string _description;

        public ServiceRequestPhoto(Stream imageStream, ServiceRequest serviceRequest)
        {
            if (imageStream == null)
                throw new ArgumentNullException("imageStream");
            if (serviceRequest == null)
                throw new ArgumentNullException("serviceRequest");
            ServiceRequest = serviceRequest;
            using (var binaryReader = new BinaryReader(imageStream)) {
                    _bytes = binaryReader.ReadBytes((int) imageStream.Length);
            }
            ValidateImage();
        }
        
        public ServiceRequest ServiceRequest { get; private set; }
        
        public string Description
        {
            get { return _description; }
            set
            {
                _description = value;
                NotifyPropertyChanged("Description");
            }
        }

        /// <summary>
        /// Gets the image as a BitmapImage.
        /// </summary>
        public BitmapImage BitmapImage
        {
            get
            {
                var image = new BitmapImage();
                image.BeginInit();
                image.CreateOptions = BitmapCreateOptions.None;
                image.CacheOption = BitmapCacheOption.Default;
                image.StreamSource = new MemoryStream(_bytes);
                image.EndInit();
                return image;
            }
        }

        private void ValidateImage()
        {
            const string errorMessage = "Tiedoston täytyy olla JPEG- tai PNG-kuva.";
            try {
                var image = new Bitmap(new MemoryStream(_bytes));
                if (!(image.RawFormat.Equals(ImageFormat.Jpeg) || image.RawFormat.Equals(ImageFormat.Png)))
                    throw new ValidationException(errorMessage);
            } catch {
                throw new ValidationException(errorMessage);
            }
        }
    }
}